 var assigneeListIndex = $('#assigneeListTable').find('tr').length-1;
 var deletedNodeOwnerIds = new Array();
 var ownerCreateType;
 var forInst;
 $(function() {
		/*$('#assigneeForm').on('init.field.bv', function(e, data) {
	        var $icon      = data.element.data('bv.icon'),
	        options    = data.bv.getOptions(),                      // Entire options
	        validators = data.bv.getOptions(data.field).validators; // The field validators
		    if (validators.notEmpty && options.feedbackIcons && options.feedbackIcons.required) {
		    	$icon.addClass(options.feedbackIcons.required).show();
		    }
		}).bootstrapValidator({
			container:'popover',
			feedbackIcons: {
				 required: 'glyphicon glyphicon-asterisk requiredStar',
				valid: 'glyphicon glyphicon-ok',
				invalid: 'glyphicon glyphicon-remove',
				validating: 'glyphicon glyphicon-refresh'
			},
			fields: {
			},group:'.validateDiv'
		}).on('success.form.bv', submitAssignee);
		
		initCommonValue();*/
		$("#ownerCreateType").change(function(){
			initCommonValue();
		});
		
		var $tr = $('#assigneeListTable tbody').find("tr");
		$tr.each(function(index){ 
			var pattern = $tr.find("select#pattern_"+index).find("option:selected").val();
			$("input#organizationNameOrg_"+index).val($("input#organizationName_"+index).val()); //保存本次部门
			$("input#organizationIdOrg_"+index).val($("input#organizationId_"+index).val());//薄层本次部门
			if("SELECTED"!=pattern){ 
				$tr.find("input#organizationName_"+index).val('');
				$tr.find("input#button_"+index).prop("disabled",true); 
//				$tr.find("select#userId_"+index).find("option:selected").text('请选择');
				$tr.find("select#userId_"+index).prop("disabled",true); 
			}
		 }); 
		
		// 流程实例管理打开处理人编辑页面
		forInst = $("#forInst").val();
		if(forInst == "0"){
//			$("#saveAssigneeBtn").attr("disabled", true);
		}
		// 因为bootstrap模态框的这个方法和select2有冲突，所以要重写此方法才能使用select2
		/*$.fn.modal.Constructor.prototype.enforceFocus = function() {
		};*/

		 /*if($('.positionSel').length>0){
				$('.positionSel').select2({
					allowClear: true,
					placeholder: common.i18n('cp.js.please_select'),
					language: "zh-CN"
				});
			}
		 if($('.userSel').length>0){
			 $('.userSel').select2({
				 allowClear: true,
				 placeholder: common.i18n('cp.js.please_select'),
				 language: "zh-CN"
			 });
		 }*/
	});
 
 function initCommonValue(){
	 ownerCreateType =$("#ownerCreateType option:selected").val();
		if(ownerCreateType=='PUSH'){
			$("#pushDiv").show();
			$("#pullDiv").hide();
			$('#pullDiv #ifForceDistribute').attr("checked",false);
			$("#jointlyDiv").hide();
			$('#jointlyDiv #ifForceDistribute').attr("checked",false);
			$('#jointlyDiv #jointlyAssign').attr("checked",false);
		}else if(ownerCreateType=='JOINTLY'){
			$("#pushDiv").hide();
			$('#pushDiv #ifForceDistribute').attr("checked",false);
			$("#pullDiv").hide();
			$('#pullDiv #ifForceDistribute').attr("checked",false);
			$("#jointlyDiv").show();
		}else if(ownerCreateType=='PULL'){ 
			$("#pushDiv").hide();
			$('#pushDiv #ifForceDistribute').attr("checked",false);
			$("#pullDiv").show();
			$("#jointlyDiv").hide();
			$('#jointlyDiv #ifForceDistribute').attr("checked",false);
			$('#jointlyDiv #jointlyAssign').attr("checked",false);
			
		}else{ 
			$("#pushDiv").hide();
			$("#pullDiv").hide();
			$('#pullDiv #ifForceDistribute').attr("checked",false);
			$("#jointlyDiv").hide();
			$('#jointlyDiv #ifForceDistribute').attr("checked",false);
		}
		
		if(ownerCreateType=='PULL'){
			$("#ffrName").removeAttr("disabled");
			$("#queryFFR").removeAttr("disabled");
		}else{
			$("#ffrName").attr("disabled",true);
			$("#queryFFR").attr("disabled",true);
			$("#ffrId").val("");
			$("#ffrName").val("");
		}
 }
 
 function saveAssignee(){
//		$('#assigneeForm').bootstrapValidator('validate');
		 var flag=true;
		 for(var i=0;i<assigneeListIndex;i++){
			 var pattern = $("select#pattern_"+i).find("option:selected").val();
			 if("SELECTED"==pattern){
					var org =  $("input#organizationName_"+i).val();
//					var postion = $("select#posId_"+i).find("option:selected").text();
//					if((org==null || org=='' || org==undefined) && (postion==undefined || postion==common.i18n('cp.js.please_select'))){
					if(org==null || org=='' || org==undefined){
							flag=false;
					}
			 } 
		}
		if(!flag){ 
			common.info(common.i18n('cp.js.tzm1'));
			return false;
		}
		 
		var len = $("#assigneeListTable tbody tr").length;
		if(len<1){
			common.info(common.i18n('cp.js.Pc0')); 
			return false;
		}
		
		if(forInst == "0"){
			 // 自动触发流程实例部署，部署成功后再保存处理人
			 var processId = $('#processId').val();
			 var instId = $('#instId').val();
			 var options = {
				success : function(data) {
					if(data.result=='true'){
						debugger;
						$('#processId').val(data.newProcessId);
						$("[name='actReProcdef.id']").val(data.newProcessId);
						enableBtn();
						
						// 保存处理人
						submitAssignee();
					}else if (data.result == 'false'){
						common.info(common.i18n('cp.js.pDn.386'));
						enableBtn();
					}else {
						enableBtn();
					}
				},
				dataType :  'json',
			};
			var runNodeKey = $('#runNodeKey').val();
			$("#processDefinition").attr("action", rcContextPath+'/procInstManage/deploy?processId='+processId+'&instId='+instId+'&runNodeKey='+runNodeKey);
			$("#processDefinition").ajaxSubmit(options); 
		 /*if(forInst == "1"){
			 $('#modifyReasonDialog').modal('toggle');*/
		 } else{
			submitAssignee();
		}
	}

function submitAssignee(){
	/*if(forInst == "1"){
		$("#adminModifyReason").val($("#reasonComment").val());
		common.closeModelDialog('modifyReasonDialog');
	}*/
	if( $(".isDefault").find("option[value='1']:selected").length>1){
		common.info(common.i18n('cp.js.pdA.114')); 
		return false;
	}
	/*if( $(".isDefault").find("option[value='1']:selected").length==0){
		common.info(common.i18n('cp.js.pdA.118')); 
		return false;
	}*/
	var processId = $("#processId").val();
	var ownerCreateType = $("#ownerCreateType").val();
	var ffrId = $("#ffrId").val();
	var ifForceDistribute = $("#ifForceDistribute").prop("checked");
	if(ownerCreateType=='PULL'&&ifForceDistribute&&ffrId==''){
		 common.info(common.i18n('cp.js.pdA.126')); 
		return false;
	}
	 $('#deletedNodeOwnerIds').val(deletedNodeOwnerIds.join(","));
	 var len = $("#assigneeListTable tbody tr").length;
	 if(len<1){
		 common.info(common.i18n('cp.js.Pc0')); 
			return false;
	 }
	if(!validateFfrName()) return false;
	
	$.ajax({
		type: "post",  
		url: rcContextPath + '/process/saveAssigneeList',
		data: $("#assigneeForm").serialize(), 
		success: function(data) {
			if(data.msg =='0'){
				 common.success(common.i18n('cp.js.submit_successfully'),function(){
					 if(forInst == "0" || forInst == "1"){
						 common.closeModelDialog('procInstAssigneeDialog');
						 if(forInst == "0"){
							 // 刷新流程编辑页面
							 var id = $('#instId').val();
							 top.addTab('tabs', '编辑流程实例', 'procInstForm'+id, rcContextPath+'/procInstManage/procInstForm?id='+id + '&mode=edit',true);
						 }
					 } else {
						 common.closeModelDialog('assigneeDialog');
						 location.href = rcContextPath+'/process/viewNode?processId='+processId;
					 }
				 });
			}else{
				common.error(common.i18n('cp.js.sw70')+data.msg);
			}
		}
	});
}


function changePosition(index){
	var positionId = $('#posId_'+index).val();
	var organId = $('#organizationId_'+index).val();
	var pattern = $("select#pattern_"+index).find("option:selected").val();
	$("#userId_"+index+" option").remove();
	$("#userId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
	if("SELECTED"==pattern){  //处理人不用处理
		 var urls="";
		 if(positionId!=''){
			 if(organId!=""){
				 urls=rcContextPath + '/activiti/getUserList?organId='+organId+'&positionId='+positionId;
			 }else{
				 urls=rcContextPath + '/activiti/getUseByPostion?positionId='+positionId;
			 }
		 }else{
			 if(organId !=''){
				 urls=rcContextPath + '/activiti/getUserByOrgList?organId='+organId;
			 }
		 }
		 if(urls!=""){
			 $.ajax({  
				type: "post",
				url: urls,
				success: function (data) {
					$.each(data, function (i, item) {
						$("#userId_"+index).append("<option value='" + item[0] +  "'>" + item[1] + "</option>"); 
					});  
					$("#userId_"+index).trigger('change');
				}
			}); 
		 }
	 }
}

function changeOrgan(index){
	   var organId = $('#organizationId_'+index).val();
	   $("input#organizationNameOrg_"+index).val($("input#organizationName_"+index).val()); //保存本次部门
	   $("input#organizationIdOrg_"+index).val($("input#organizationId_"+index).val());//薄层本次部门
	   
	   $.ajax({
		   type:"post",
		   url: rcContextPath+'/activiti/getUserByOrgList?organId='+organId,
		   success:function(data){
			   $("#userId_"+index+" option").remove();
			   $("#userId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
			   $.each(data,function(i,item){
				   $("#userId_"+index).append("<option value='"+item[0]+"'>"+item[1]+"</option>");
			   });
			   $("#userId_"+index).trigger('change');
			   getPostionFromOrg(organId,index);
		   }
	   });
		   
}
//选中部门获得 岗位----从部门下人员及管理人员 关联岗位
function getPostionFromOrg(organId,index){
//  岗位
	   $.ajax({  
	       type: "post",
	       url: rcContextPath + '/activiti/getPositionList?organId='+organId,
	       success: function (data) {
	           $("#posId_"+index+" option").remove();
	           $("#posId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
	           $.each(data, function (i, item) {
	        	   if(sessionLocale != 'zh_CN' && item[4]){
	        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[4] + "</option>");
	        	   } else {
	        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[2] + "</option>"); 
	        	   }
	           });
	           $("#posId_"+index).trigger('change');
	       }
	   });  
}


function changePattern(index){
	var pattern = $("select#pattern_"+index).val();
	if("MEETING"==pattern){
		$(".meetingDiv"+index).show();
		$(".meetingDivN"+index).hide();
		$(".meetingDiv").show();
		$("input#organizationName_"+index).val('');//部门置空
		$("input#organizationId_"+index).val(''); //部门id置空
		$("input#organizationNameOrg_"+index).val(''); //部门id置空
		$("input#organizationIdOrg_"+index).val(''); //部门id置空
		$("#userId_"+index).val(''); //用户id置空
		$("#posId_"+index).val(''); //岗位id置空
	}else{
		$("#meetingConfigId"+index).val(''); //会议类型id
		$("#meetingRole"+index).val(''); //会议角色
		$(".meetingDiv"+index).hide();
		$(".meetingDivN"+index).show();
		if("SELECTED"==pattern){
			$("input#button_"+index).prop("disabled",false);//部门可选
			$("select#userId_"+index).prop("disabled",false);//处理人可选
			$("input#organizationName_"+index).val($("input#organizationNameOrg_"+index).val()); //部门  显示上次值
			$("input#organizationId_"+index).val($("input#organizationIdOrg_"+index).val());//部门id 显示上次值
		  
		}else {
			$("input#button_"+index).prop("disabled",true);//部门不可选
			$("select#userId_"+index).prop("disabled",true); //处理人不可选
			$("input#organizationName_"+index).val('');//部门置空
			$("input#organizationId_"+index).val(''); //部门id置空
		}
		$.ajax({  //刷新岗位
		       type: "post",
		       url: rcContextPath + '/activiti/getPositionList?organId=',
		       success: function (data) {
		           $("#userId_"+index+" option").remove();
				   $("#userId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
		           $("#posId_"+index+" option").remove();
		           $("#posId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
		           $.each(data, function (i, item) {
		        	   if(sessionLocale == 'en_US' && item[4]){
		        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[4] + "</option>");
		        	   } else {
		        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[2] + "</option>");
		        	   }
		           });
		   			$("#posId_"+index).trigger('change');
					$("#userId_"+index).trigger('change');
		       }
		   });
	}
}

//选中部门获得 岗位----从部门下人员及管理人员 关联岗位
function getPostionFromOrg(organId,index){
//  岗位
	   $.ajax({  
	       type: "post",
	       url: rcContextPath + '/activiti/getPositionList?organId='+organId,
	       success: function (data) {
	           $("#posId_"+index+" option").remove();
	           $("#posId_"+index).append("<option value=''>"+common.i18n('cp.js.please_select')+"</option>");
	           $.each(data, function (i, item) {
	        	   if(sessionLocale != 'zh_CN' && item[4]){
	        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[4] + "</option>");
	        	   } else {
	        		   $("#posId_"+index).append("<option value='" + item[0] +  "'>" + item[2] + "</option>");
	        	   }
	           });
	           $("#posId_"+index).trigger('change');
	           /*$("#posId_"+index).select2('destroy').empty();
	           $("#posId_"+index).select2({
					allowClear: true,
					placeholder: common.i18n('cp.js.please_select'),
					language: "zh-CN"
				});*/
	       }
	   });  
}

function addAssigneeList(){
	var obj = $('#assigneeListTemTable').find('tr').clone();
	var index=assigneeListIndex;
	obj.html(obj.html().replace(/{@namevalue@}/g, assigneeListIndex++));
	$("#assigneeListTable").append(obj);
	/*$("#posId_"+index).select2({
				allowClear: true,
				placeholder: common.i18n('cp.js.please_select'),
				language: "zh-CN"
			});
	$("#userId_"+index).select2({
		allowClear: true,
		placeholder: common.i18n('cp.js.please_select'),
		language: "zh-CN"
	});*/
};


function setDefault(name){
	var checkedlen= $("#assigneeListTable tr").find("input[type=checkbox]:checked").length;
	var nodeId = $('#nodeId').val();
	var processId = $('#processId').val();
	if(checkedlen != 1){
		common.info(common.i18n('cp.js.sw07'));
		return;
	}else{
		var id = $("input[name=" + name + "]:checked").eq(0).attr('id');
		$.ajax({
			type:"post",
			url: rcContextPath + '/process/setDefault?id='+id+'&nodeId='+nodeId+'&processId='+processId,   
			success:function(msg){
				$("#grid-ChangeApproval").bootgrid("search","");
				location.href = rcContextPath+'/process/addAssignee?nodeId='+nodeId+'&processId='+processId;
			}
		});
	}

}

//删除担保措施
function delAssigneeList(name){
	var checkedlen= $("#assigneeListTable tr").find("input[type=checkbox]:checked").length;
	if(checkedlen < 1){
		common.info(common.i18n('cp.js.p40'));
		return;
	}
	var checkBoxs=$("input[name=" + name + "]:checked");
	common.confirm(common.i18n('cp.js.a1'),function(){
		checkBoxs.each(function(i) {
			if($(this).attr('id')) {
				deletedNodeOwnerIds.push($(this).attr('id'));
			}
			$(this).parent().parent().remove();
		});
	});
}

function addDistributor(){
	$.ajax({
		type : "post",
		url: rcContextPath + '/process/addDistributor', 
		data: $("#distributorForm").serialize(), 
		success : function(data) {
			$('#distributorDialog').html(data);
			$('#distributorDialog').modal('toggle');
		}
	});
}

function validateFfrName(){
	if($('#pullDiv').find('#ifForceDistribute').is(':checked')){
		var ffrId=$('#pullDiv').find('#ffrId').val();
		if(ffrId==undefined || ffrId==''){
			common.info('必须分发时 分发人必填'); 
			return false;
		}
	}
	return true;
}

function addOrganization(){
	// TODO: 选择部门
}